package cc.z8g.browser.incognito

import android.app.Activity
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.os.Build
import androidx.core.app.NotificationCompat
import cc.z8g.browser.IncognitoBrowserActivity
import cc.z8g.browser.R
import cc.z8g.browser.utils.SystemServiceManager
import cc.z8g.browser.utils.ThemeUtils

/**
 * 一个通知助手，在通知中显示当前打开的标签数作为警告。当点击通知时，隐身浏览器将会打开。
 */
object IncognitoNotification {

    private const val ID_INCOGNITO = 1
    private const val CHANNEL_INCOGNITO = "channel_incognito"

    fun notifyTabCountChange(total: Int, activity: Activity?) {
        if (activity == null) {
            return
        }
        init(activity)
        if (total > 0) {
            show(activity, total)
        } else {
            hide()
        }
    }


    private fun init(activity: Activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelName = activity.getString(R.string.notification_incognito_running_description)
            val channel = NotificationChannel(CHANNEL_INCOGNITO, channelName, NotificationManager.IMPORTANCE_LOW)
            channel.enableVibration(false)
            SystemServiceManager.notificationManager.createNotificationChannel(channel)
        }
    }


    /** 显示提供的标签数的通知。如果通知已存在，则将其更新。 */
    private fun show(activity: Activity, number: Int) {
        if (number <= 0) {
            return
        }
        val incognitoIntent = IncognitoBrowserActivity.intent(activity)

        val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else 0
        val incognitoNotification = NotificationCompat.Builder(activity, CHANNEL_INCOGNITO)
            .setSmallIcon(R.drawable.ic_notification_incognito)
            .setContentTitle(activity.resources.getQuantityString(R.plurals.notification_incognito_running_title, number, number))
            .setContentIntent(PendingIntent.getActivity(activity, 0, incognitoIntent, flags))
            .setContentText(activity.getString(R.string.notification_incognito_running_message))
            .setAutoCancel(false)
            .setColor(ThemeUtils.getAccentColor(activity))
            .setOngoing(true)
            .build()

        SystemServiceManager.notificationManager.notify(ID_INCOGNITO, incognitoNotification)
    }

    /** 隐藏通知 */
    private fun hide() = SystemServiceManager.notificationManager.cancel(ID_INCOGNITO)

}
